<template>
  <div class="dashboard">
    <h1>智慧大棚实时监控</h1>

    <!-- 顶部信息栏 -->
    <el-row :gutter="20" class="info-row">
      <el-col :span="6">
        <dv-border-box-1 class="info-box">
          <h3>智慧大棚编号</h3>
          <p>{{ boxNo }}</p>
        </dv-border-box-1>
      </el-col>
      <el-col :span="6">
        <dv-border-box-1 class="info-box">
          <h3>占地面积</h3>
          <p>0.68 亩</p>
        </dv-border-box-1>
      </el-col>
      <el-col :span="6">
        <dv-border-box-1 class="info-box">
          <h3>生长阶段</h3>
          <p>开花结果期</p>
        </dv-border-box-1>
      </el-col>
      <el-col :span="6">
        <dv-border-box-1 class="info-box">
          <h3>土壤PH值</h3>
          <dv-active-ring-chart :config="phGaugeConfig" style="height: 120px;" />
          <p class="ph-value">{{ soilData['土壤PH值'] }}</p>
        </dv-border-box-1>
      </el-col>
    </el-row>

    <!-- 数据展示区域 -->
    <el-row :gutter="20" class="data-row">
      <!-- 左侧数据 -->
      <el-col :span="12">
        <dv-border-box-8 class="data-box">
          <h3>土壤数据</h3>
          <el-row :gutter="10">
            <el-col :span="8">
              <div class="data-item">
                <h4>土壤含水率</h4>
                <p>{{ soilData['土壤含水率'] }}%</p>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="data-item">
                <h4>土壤电导率</h4>
                <p>{{ soilData['土壤电导率'] }} µS/cm</p>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="data-item">
                <h4>土壤温度</h4>
                <p>{{ soilData['土壤温度'] }} ℃</p>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="data-item">
                <h4>土壤氮含量</h4>
                <p>{{ soilData['土壤氮含量'] }} mg/kg</p>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="data-item">
                <h4>土壤磷含量</h4>
                <p>{{ soilData['土壤磷含量'] }} mg/kg</p>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="data-item">
                <h4>土壤钾含量</h4>
                <p>{{ soilData['土壤钾含量'] }} mg/kg</p>
              </div>
            </el-col>
          </el-row>
        </dv-border-box-8>
      </el-col>

      <!-- 右侧数据 -->
      <el-col :span="12">
        <dv-border-box-8 class="data-box">
          <h3>环境数据</h3>
          <el-row :gutter="10">
            <el-col :span="12">
              <div class="data-item">
                <h4>空气温度</h4>
                <p>{{ environmentData['空气温度'] }} ℃</p>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="data-item">
                <h4>空气湿度</h4>
                <p>{{ environmentData['空气相对湿度'] }}%RH</p>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="data-item">
                <h4>二氧化碳</h4>
                <p>{{ environmentData['二氧化碳'] }} ppm</p>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="data-item">
                <h4>光照度</h4>
                <p>{{ environmentData['光照度'] }} Lux</p>
              </div>
            </el-col>
          </el-row>
        </dv-border-box-8>
      </el-col>
    </el-row>

    <!-- 照片与视频区域 -->
    <el-row :gutter="20" class="media-row">
      <el-col :span="12">
        <dv-border-box-13 class="media-box">
          <h3>监控照片</h3>
          <div v-if="photoUrl">
            <img :src="photoUrl" alt="监控照片" class="media-image" />
          </div>
          <p v-else-if="photoLoading">正在加载照片...</p>
          <p v-else style="color: red;">照片加载失败，请检查网络或后端服务。</p>
        </dv-border-box-13>
      </el-col>
      <el-col :span="12">
        <dv-border-box-13 class="media-box">
          <h3>实时视频</h3>
          <div id="ys_player" style="height: 50vh; width: 100%;"></div>
        </dv-border-box-13>
      </el-col>
    </el-row>

    <!-- 底部滚动栏 -->
    <el-row class="scroll-row">
      <el-col :span="24">
        <dv-border-box-12 class="scroll-box">
          <h3>实时环境监测</h3>
          <dv-scroll-board :config="chartConfig" style="height: 200px;" />
        </dv-border-box-12>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import EZUIKit from 'ezuikit-js';

// 土壤数据和照片相关代码
const soilData = ref({});
const environmentData = ref({});
const boxNo = ref('8014679018257413002');
const photoUrl = ref('');
const photoLoading = ref(true);

// 获取土壤数据
const fetchSoilData = async () => {
  try {
    const response = await axios.post('http://localhost:8080/api/soil-data/fetch');
    console.log('土壤数据响应：', response.data);
    if (response.data.code === 200) {
      response.data.data.forEach((item: any) => {
        if (item.name.includes('土壤')) {
          soilData.value[item.name] = item.value;
        } else {
          environmentData.value[item.name] = item.value;
        }
      });
    } else {
      console.error('获取土壤数据失败：', response.data.message);
    }
  } catch (error) {
    console.error('请求失败：', error);
  }
};

// 获取照片
const fetchPhoto = async () => {
  try {
    const params = new URLSearchParams();
    params.append('deviceSerial', 'L29334649');
    params.append('quality', '1');

    const response = await axios.post('http://localhost:8080/api/camera/capture', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
    if (response.data.code === 200) {
      photoUrl.value = response.data.data.address;
    } else {
      console.error('获取照片失败：', response.data.message);
    }
  } catch (error) {
    console.error('请求失败：', error);
  } finally {
    photoLoading.value = false;
  }
};

// 视频监控相关代码
let player;

// 解决 AudioContext 错误
const resumeAudioContext = () => {
  const audioContext = new AudioContext();
  if (audioContext.state === 'suspended') {
    audioContext.resume().then(() => {
      console.log('AudioContext resumed');
    });
  }
};

// 抓拍功能
const capturePicture = async () => {
  try {
    const accessToken = await getToken();
    const response = await post('/api/ys/capture', {
      accessToken,
      deviceSerial: 'L29334649',
      channelNo: 1,
      quality: 1,
    });
    if (response.code === '200') {
      console.log('抓拍成功');
    } else {
      console.error('抓拍失败:', response.msg);
    }
  } catch (error) {
    console.error('抓拍出错:', error);
  }
};

// 获取 Token
const getToken = async () => {
  try {
    const storedToken = localStorage.getItem('ys_token');
    const storedExpireTime = localStorage.getItem('ys_token_expire');
    if (storedToken && storedExpireTime && Date.now() < parseInt(storedExpireTime)) {
      return storedToken;
    }
    const response = await post('http://localhost:8080/api/token/video', {});
    if (response.code !== '200') {
      throw new Error('获取 Token 失败: ' + response.msg);
    }
    const { accessToken, expireTime } = response.data;
    localStorage.setItem('ys_token', accessToken);
    localStorage.setItem('ys_token_expire', expireTime);
    return accessToken;
  } catch (error) {
    console.error('获取 Token 出错:', error);
    throw error;
  }
};

// 封装 POST 请求
const post = async (url: string, data: any) => {
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  });
  return response.json();
};

// 初始化播放器
const init = async () => {
  if (player) {
    player.destroy();
    player = null;
  }
  const container = document.getElementById('ys_player');
  if (!container) {
    console.error('Video container not found');
    return;
  }
  try {
    const accessToken = await getToken();
    player = new EZUIKit.EZUIKitPlayer({
      id: 'ys_player',
      accessToken: accessToken,
      url: 'ezopen://open.ys7.com/L29334649/1.hd.live',
      template: 'simple',
      plugin: ['talk'],
      autoplay: true,
      handleError: async (err: any) => {
        console.error('播放器错误:', err);
        if (err.code === 401) {
          localStorage.removeItem('ys_token');
          localStorage.removeItem('ys_token_expire');
          init();
        }
      },
      env: {
        domain: 'https://open.ys7.com',
      },
    });
    window.player = player;
  } catch (error) {
    console.error('Failed to initialize player:', error);
  }
};

// 组件挂载后初始化播放器
onMounted(() => {
  setTimeout(() => {
    init();
  }, 100);
  fetchSoilData();
  fetchPhoto();
});

// 用户交互后恢复 AudioContext
document.addEventListener('click', resumeAudioContext);

// 码表配置
const phGaugeConfig = ref({
  data: [
    { name: 'PH值', value: 3.0 },
  ],
  color: ['#37a2da'],
  radius: '60%',
  activeRadius: '70%',
  digitalFlopStyle: {
    fontSize: 20,
  },
});

// 图表配置
const chartConfig = ref({
  header: ['时间', '温度', '湿度'],
  data: [
    ['10:00', '27.8℃', '65.8%RH'],
    ['11:00', '28.1℃', '66.2%RH'],
    ['12:00', '28.5℃', '66.5%RH'],
    ['13:00', '28.3℃', '66.0%RH'],
    ['14:00', '28.0℃', '65.8%RH'],
    ['15:00', '27.9℃', '65.7%RH'],
    ['16:00', '27.7℃', '65.5%RH'],
    ['17:00', '27.5℃', '65.3%RH'],
    ['18:00', '27.3℃', '65.1%RH'],
    ['19:00', '27.1℃', '64.9%RH'],
  ],
  index: true,
  columnWidth: [100, 150, 150],
  align: ['center'],
  headerBGC: '#1980ff',
  oddRowBGC: '#1a2735',
  evenRowBGC: '#1a2735',
});
</script>

<style scoped>
.dashboard {
  padding: 20px;
  font-family: Arial, sans-serif;
  background-color: #0a1a2f;
  color: #fff;
  min-height: 100vh;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  font-size: 28px;
  color: #fff;
}

.info-row,
.data-row,
.media-row,
.scroll-row {
  margin-bottom: 20px;
}

.info-box,
.data-box,
.media-box,
.scroll-box {
  padding: 20px;
  text-align: center;
  background-color: #1a2735;
  border-radius: 8px;
  color: #fff;
}

.data-item {
  padding: 10px;
  background-color: #2a3a4f;
  border-radius: 8px;
  margin-bottom: 10px;
}

h3 {
  margin-bottom: 15px;
  font-size: 20px;
  color: #fff;
}

h4 {
  margin-bottom: 5px;
  font-size: 16px;
  color: #fff;
}

p {
  font-size: 14px;
  color: #fff;
}

.ph-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 10px;
}

.media-box {
  padding: 20px;
  text-align: center;
}

.media-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
  border: 2px solid #1980ff;
}

.video-placeholder {
  padding: 50px;
  background-color: #2a3a4f;
  border-radius: 8px;
  border: 2px solid #1980ff;
  color: #fff;
  text-align: center;
}

.scroll-box {
  padding: 20px;
  background-color: #1a2735;
  border-radius: 8px;
}
</style>